package com.atlin.project.service.impl;

import com.atlin.project.common.ErrorCode;
import com.atlin.project.exception.BusinessException;
import com.atlin.project.exception.ThrowUtils;
import com.atlin.project.model.vo.serviceUsage.ServiceUsageVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atlin.project.model.domain.ServiceUsage;
import com.atlin.project.service.ServiceUsageService;
import com.atlin.project.mapper.ServiceUsageMapper;
import org.springframework.stereotype.Service;

/**
 * @author atlin
 * @description 针对表【service_usage(用户AI服务表)】的数据库操作Service实现
 * @createDate 2024-11-23 15:00:29
 */
@Service
public class ServiceUsageServiceImpl extends ServiceImpl<ServiceUsageMapper, ServiceUsage>
        implements ServiceUsageService {

    /**
     * 初始化数据
     *
     * @param userId
     * @return
     */
    private boolean initServiceUsage(Long userId) {
        ServiceUsage serviceUsage = new ServiceUsage();
        serviceUsage.setUserId(userId);
        return save(serviceUsage);
    }

    @Override
    public Long getLeftTokens(Long userId) {
        QueryWrapper<ServiceUsage> wrapper = new QueryWrapper<>();
        wrapper.eq("userId", userId);
        ServiceUsage serviceUsage = this.getOne(wrapper);

        if (serviceUsage == null) return 0L;

        return serviceUsage.getLeftTokens();
    }

    @Override
    public Boolean updateTokens(Long userId, Long tokens, boolean invoke) {
        if (userId < 0 || tokens < 0) {
            return true;
        }
        ServiceUsage serviceUsage = getServiceUsageByUserId(userId);
        if (serviceUsage == null) {
            // 初始化数据
            initServiceUsage(userId);
        }
        UpdateWrapper<ServiceUsage> wrapper = new UpdateWrapper<>();
        wrapper.lambda().eq(ServiceUsage::getUserId, userId);

        if (invoke) {
            wrapper.setSql("leftTokens=leftTokens - " + tokens + " ,tokensConsumed = tokensConsumed + "
                    + tokens + ", useCount = useCount+1");
        } else {
            wrapper.setSql("leftTokens=leftTokens+" + tokens);
        }
        return update(wrapper);
    }

    @Override
    public ServiceUsage getServiceUsageByUserId(Long userId) {
        if (userId == null || userId <= 0) return null;
        QueryWrapper<ServiceUsage> wrapper = new QueryWrapper<>();
        wrapper.eq("userId", userId);

        return getOne(wrapper);
    }

    @Override
    public ServiceUsageVO getServiceUsageVO(ServiceUsage serviceUsage) {
        // Todo
        return null;
    }
}




